package www.openteam.com.ui.realtime;

import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.CardView;
import android.text.method.ScrollingMovementMethod;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.cundong.recyclerview.EndlessRecyclerOnScrollListener;
import com.cundong.recyclerview.HeaderAndFooterRecyclerViewAdapter;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import www.openteam.com.R;
import www.openteam.com.adapter.DeliverGoodAdapter;
import www.openteam.com.base.mBaseFragment;
import www.openteam.com.bean.DeliverGoods;
import www.openteam.com.contract.realtime.DeliverGoodsContract;
import www.openteam.com.presenter.realtime.DeliverGoodsPresenter;
import www.openteam.com.tool.RecyclerViewStateUtils;
import www.openteam.com.tool.ToastUtil;
import www.openteam.com.ui.DetailedActivity;
import www.openteam.com.widget.LoadingFooter;

/**
 * Created by hyd on 2016/10/15.
 * 采购进度 4
 */

public class DeliverGoodFragment extends mBaseFragment<DeliverGoodsPresenter>
        implements DeliverGoodsContract.DeliverGoodsView, SwipeRefreshLayout.OnRefreshListener {

    @Bind(R.id.ed_1)
    EditText ed_1;
    @Bind(R.id.ed_2)
    EditText ed_2;
    @Bind(R.id.ed_3)
    EditText ed_3;
    @Bind(R.id.ed_4)
    EditText ed_4;
    @Bind(R.id.query_btn)
    Button query_btn;
    @Bind(R.id.tv_1)
    TextView tv_1;
    @Bind(R.id.tv_2)
    TextView tv_2;
    @Bind(R.id.tv_3)
    TextView tv_3;
    @Bind(R.id.tv_4)
    TextView tv_4;
//    @Bind(R.id.detial)
//    LinearLayout detial;
    @Bind(R.id.btn1)
    Button btn1;
    @Bind(R.id.btn2)
    Button btn2;
    @Bind(R.id.btn3)
    Button btn3;
    @Bind(R.id.btn)
    LinearLayout btn;
    @Bind(R.id.tv_title)
    TextView tv_5;
    @Bind(R.id.card)
    CardView cardView;
    int j = -1;


    private ArrayList<DeliverGoods.DataEntity> deliverGoodses;          //送货进度实体类
    private static int pageSize = 0;
    private final String TAG = DeliverGoodFragment.class.getSimpleName();
    int i = 0;
    private HeaderAndFooterRecyclerViewAdapter mFooterRecyclerViewAapter = null;
    private DeliverGoodAdapter deliverGoodsAdapter = null;
    Throwable throwable = null;


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        detailGather = ((DetailedActivity) getActivity()).getDetailGather();
    }

    @Override
    protected void initData() {

    }

    @Override
    protected void initListener() {
        measurementLayoutHeight();
    }


    @Override
    protected void initView() {
        tv_5.setMovementMethod(ScrollingMovementMethod.getInstance());
        final SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        Calendar c = Calendar.getInstance();
        int current_day = c.get(Calendar.DAY_OF_MONTH);
        int current_month = c.get(Calendar.MONTH);
        int current_year = c.get(Calendar.YEAR);
        c.set(current_year, current_month, current_day);
        ed_3.setText(df.format(c.getTime()));
        btn1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {//一周内
                Calendar c = Calendar.getInstance();
                int current_day = c.get(Calendar.DAY_OF_MONTH);
                int current_month = c.get(Calendar.MONTH);
                int current_year = c.get(Calendar.YEAR);
                c.set(current_year, current_month, current_day);
                c.add(Calendar.DATE, -7);
                ed_4.setText(df.format(c.getTime()));
            }
        });

        btn2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {//一月内
                Calendar c = Calendar.getInstance();
                int current_day = c.get(Calendar.DAY_OF_MONTH);
                int current_month = c.get(Calendar.MONTH) - 1;
                int current_year = c.get(Calendar.YEAR);
                c.set(current_year, current_month, current_day);
//                ed_3.setText(df.format(c.getTime()));
//                c.add(Calendar.DATE, 0);
                ed_4.setText(df.format(c.getTime()));
            }
        });

        btn3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {//一年内
                Calendar c = Calendar.getInstance();
                int current_day = c.get(Calendar.DAY_OF_MONTH);
                int current_month = c.get(Calendar.MONTH);
                int current_year = c.get(Calendar.YEAR) - 1;
                c.set(current_year, current_month, current_day);
//                ed_3.setText(df.format(c.getTime()));
//                c.add(Calendar.DATE, 0);
                ed_4.setText(df.format(c.getTime()));
            }
        });

        query_btn.setOnClickListener(new View.OnClickListener() {  //查询按钮
            @Override
            public void onClick(View v) {
//                SharedPreferences getMysetting = getContext().getSharedPreferences("mySetting", Context.MODE_PRIVATE);

                createProgressDialog("正在查询,请稍候...");
                if (deliverGoodsAdapter == null) {
                    deliverGoodses = new ArrayList<DeliverGoods.DataEntity>();
                    mPresenter.queryDeliverGoods(getRdsno(), getCustid(), getStartDate(),
                            getEndDate(), getStype(), getMoreCom(), getUserId(), getJMark(), pageSize);
                } else {
                    deliverGoodsAdapter.deleteItems(deliverGoodses);
                    deliverGoodses.clear();
//                    deliverGoodsAdapter.notifyDataSetChanged();
//                    mFooterRecyclerViewAapter.notifyDataSetChanged();
//                    mRecyclerView.removeAllViews();
                    throwable = null;
                    i = 0;
                    onRefresh();
                }


            }
        });
    }

    @Override
    protected void otherViewClick(View view) {


        ed_4.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.e(TAG, "onClick: ");
                selectCalendar();
            }
        });
        ed_3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                selectEndCalendar();
            }
        });

    }

    @Override
    protected DeliverGoodsPresenter loadPresenter() {
        return new DeliverGoodsPresenter();
    }

    @Override
    public String getRdsno() {
        return ed_2.getText().toString();
    }

    @Override
    public String getCustid() {
        return ed_1.getText().toString();
    }

    @Override
    public long getStartDate() {
        if (!ed_4.getText().toString().isEmpty()) {
            startMilli = changeMilli(ed_4.getText().toString());

        }
        return startMilli;
    }

    @Override
    public long getEndDate() {
        if (!ed_3.getText().toString().isEmpty()) {
            endMilli = changeMilli(ed_3.getText().toString());
        }
        return endMilli;
    }

    @Override
    public String getStype() {
        String stype = mySetting.getString("rCode", "");
        Log.d(TAG, "getStype: " + stype);
        return stype;
    }

    @Override
    public String getMoreCom() {
        String moreCom = mySetting.getString("rMoreCom", "");
//        Log.d(TAG, "getMoreCom: "+moreCom);
        return moreCom;
    }

    @Override
    public int getUserId() {
        int userId = mySetting.getInt("mId", 0);
        return userId;
    }

    @Override
    public String getJMark() {
        boolean isSale = mySetting.getBoolean("isSale", false);
        int grpAuthority = mySetting.getInt("groupAuthority", 0);
        Log.d(TAG, "getJMark: " + grpAuthority + ":" + isSale);
        if (isSale && grpAuthority == 0) {
            return "1";
        } else if (!isSale && grpAuthority == 0) {
            return "0";
        } else {
            return "2";
        }

    }


    @Override
    public void queryDGSuccess(final List<DeliverGoods.DataEntity> data) {
        mProgressDialog.dismiss();
        j++;
        for (DeliverGoods.DataEntity dev : data) {
            deliverGoodses.add(dev);
        }
        setDeliverGoodAdapter();
        cardView.setVisibility(View.VISIBLE);
        if (j==0){//第一次加载
            DeliverGoods.DataEntity item = data.get(0);
            String cN;
            if (item.getCustSName() != null) {
                cN = item.getCustSName();
            } else {
                cN = item.getCustName();
            }
            tv_5.setText("客户单号:\t" + item.getCustorderid() + "\n" + "客户名称:\t" + cN
                    + "\n" + "订单日期:\t" + item.getSenddate() +
                    "\n" + "产品名称:\t" + item.getProdName() + "\n" + "订单数量:\t" + item.getPricenumb() +
                    "\n" + "送货日期:\t" + item.getSenddate() + "\n" + "送货数:\t\t\t" + item.getPaynumb() +
                    "\n" + "退货数:\t\t\t" + item.getBacknumb() + "\n" + "未送余数:\t" + item.getNotSendNumb()
            );

        }
        deliverGoodsAdapter.setOnLineClickListener(new DeliverGoodAdapter.OnLineClickListener() {
            @Override
            public void onClick(DeliverGoods.DataEntity item) {
                String cN;
                if (item.getCustSName() != null) {
                    cN = item.getCustSName();
                } else {
                    cN = item.getCustName();
                }
                Log.e(TAG, "onClick: "+ item.getCustorderid());
                tv_5.setText("客户单号:\t" + item.getCustorderid() + "\n" + "客户名称:\t" + cN
                        + "\n" + "订单日期:\t" + item.getSenddate() +
                        "\n" + "产品名称:\t" + item.getProdName() + "\n" + "订单数量:\t" + item.getPricenumb() +
                        "\n" + "送货日期:\t" + item.getSenddate() + "\n" + "送货数:\t\t\t" + item.getPaynumb() +
                        "\n" + "退货数:\t\t\t" + item.getBacknumb() + "\n" + "未送余数:\t" + item.getNotSendNumb()
                );
            }
        });
//        if (arrow_statue) {
//            touchEvent();
//        }
    }

    @Override
    public void queryDGFail(String failMsg) {
        mProgressDialog.dismiss();
        throwable = new Throwable();
        if (failMsg.equals("暂无合适的数据")) {

            Log.d(TAG, "queryDGFail: bjg");
//            if (mRecyclerView.getChildCount() > 0) {
////                deliverGoodses.clear();\
////                  deliverGoodsAdapter.deleteItems(deliverGoodses);
//                mFooterRecyclerViewAapter.notifyDataSetChanged();
////                deliverGoodsAdapter.notifyDataSetChanged();
//                Log.d(TAG, "queryDGFail: " + mRecyclerView.getChildCount());
//
//                mRecyclerView.removeAllViews();
//            }
            RecyclerViewStateUtils.setFooterViewState(getActivity(),
                    mRecyclerView, REQUEST_COUNT, LoadingFooter.State.TheEnd, null);
            ToastUtil.showToast(getActivity(), failMsg);
        } else {
            RecyclerViewStateUtils.setFooterViewState(getActivity(), this.mRecyclerView, REQUEST_COUNT, LoadingFooter.State.NetWorkError, this.mFooterClick);
            ToastUtil.showToast(getActivity(), "网络连接有误");
        }
    }


    private void setDeliverGoodAdapter() {
        if (deliverGoodsAdapter == null) {
            deliverGoodsAdapter = new DeliverGoodAdapter(getActivity());
            deliverGoodsAdapter.addItems(deliverGoodses);
            deliverGoodsAdapter.addContext(getActivity());
            mFooterRecyclerViewAapter = new HeaderAndFooterRecyclerViewAdapter(deliverGoodsAdapter);
            mRecyclerView.setAdapter(mFooterRecyclerViewAapter);
            RecyclerViewStateUtils.setFooterViewState(this.mRecyclerView, LoadingFooter.State.Normal);
        } else {
//            Log.d(TAG, "setNewAdapter: 2" );
            mFooterRecyclerViewAapter.notifyDataSetChanged();
            deliverGoodsAdapter.addItems(deliverGoodses);
            RecyclerViewStateUtils.setFooterViewState(this.mRecyclerView,
                    LoadingFooter.State.Normal);
        }
    }


    public EndlessRecyclerOnScrollListener mOnScrollListener = new EndlessRecyclerOnScrollListener() {

        @Override
        public void onLoadNextPage(View view) {
            super.onLoadNextPage(view);
            LoadingFooter.State state = RecyclerViewStateUtils.getFooterViewState(mRecyclerView);
//            Log.d(TAG, "onLoadNextPage: yx:" + (throwable != null)+":"+(deliverGoodses.size()%10==0));
            if (state == LoadingFooter.State.Loading) {
//                Log.d("@Cundong", "the state is Loading, just wait..");
                i++;
            }
            i++;
            if (throwable == null && (deliverGoodses.size() % 10 == 0)) {

                deliverGoodses = new ArrayList<DeliverGoods.DataEntity>();
                mPresenter.queryDeliverGoods(getRdsno(), getCustid(), getStartDate(),
                        getEndDate(), getStype(), getMoreCom(), getUserId(), getJMark(), i);
                RecyclerViewStateUtils.
                        setFooterViewState(getActivity(), mRecyclerView, REQUEST_COUNT,
                                LoadingFooter.State.Loading, null);
            } else if (throwable == null && (deliverGoodses.size() % 10 != 0)) {
                //the end
//                Log.d(TAG, "onLoadNextPage:  !-9 ");
                mPresenter.queryDeliverGoods(getRdsno(), getCustid(), getStartDate(),
                        getEndDate(), getStype(), getMoreCom(), getUserId(), getJMark(), i);
                RecyclerViewStateUtils.setFooterViewState(getActivity(), mRecyclerView, REQUEST_COUNT, LoadingFooter.State.TheEnd, null);
                throwable = null;
            } else if (throwable != null) {
                //the end
                i = 0;
                if (throwable.toString().equals("com.google.gson.JsonSyntaxException:java.lang.IllegalStateException: Expected BEGIN_ARRAY but was STRING at line 1 column 42 path $.data")) {
//                    Log.d(TAG, "onLoadNextPage:  bunull ");
                    RecyclerViewStateUtils.setFooterViewState(getActivity(), mRecyclerView, REQUEST_COUNT, LoadingFooter.State.TheEnd, null);
                    throwable = null;
                }
            }

        }
    };


    private View.OnClickListener mFooterClick = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            RecyclerViewStateUtils.setFooterViewState(getActivity(), mRecyclerView, REQUEST_COUNT, LoadingFooter.State.Loading, null);
            mPresenter.queryDeliverGoods(getRdsno(), getCustid(), getStartDate(), getEndDate()
                    , getStype(), getMoreCom(), getUserId(), getJMark(), i);
        }
    };


    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        tv_1.setText(detail[0]);
        tv_2.setText(detail[1]);
        tv_3.setText(detail[2]);
        tv_4.setText(detail[3]);
        initSRView(view);
        mRecyclerView.addOnScrollListener(mOnScrollListener);
    }

    @Override
    public void onRefresh() {
        if ((mRecyclerView.getChildCount() > 0) && (!getRdsno().isEmpty() ||
                !getCustid().isEmpty() || getStartDate() != 0 || getEndDate() != 0)) {
//            mRecyclerView.removeAllViews();
//            deliverGoodses.clear();
//            deliverGoodsAdapter = null;
//            mFooterRecyclerViewAapter = null;
//            Log.d(TAG, "onRefresh: " + getStartDate());
            mPresenter.queryDeliverGoods(getRdsno(), getCustid(), getStartDate(), getEndDate(),
                    getStype(), getMoreCom(), getUserId(), getJMark(), 0);
            throwable = null;
            i = 0;
            mSwipeRefresh.setRefreshing(false);
        } else if ((mRecyclerView.getChildCount() <= 0) && (!getRdsno().isEmpty() || !getCustid().isEmpty() || getStartDate() != 0 || getEndDate() != 0)) {
//            Log.d(TAG, "onRefresh: else if " + mRecyclerView.getChildCount());
            mRecyclerView.removeAllViews();
            deliverGoodsAdapter = null;
            mFooterRecyclerViewAapter = null;
            deliverGoodses.clear();
            mPresenter.queryDeliverGoods(getRdsno(), getCustid(), getStartDate(),
                    getEndDate(), getStype(), getMoreCom(), getUserId(), getJMark(), 0);
            mSwipeRefresh.setRefreshing(false);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // TODO: inflate a fragment view
        View rootView = super.onCreateView(inflater, container, savedInstanceState);
        ButterKnife.bind(this, rootView);
        return rootView;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }
}
